<template>
  <div class="chat-item flex py-[12px]" @click="handleJump">
    <div class="flex items-center mr-[10px]">
      <div
        class="w-[8px] h-[8px] rounded-[8px]"
        :class="{
          'bg-gray-300': item.Online === 0,
          'bg-[#67C23A]': item.Online === 1
        }"
      ></div>
    </div>
    <div class="w-[57px] h-[57px]">
      <van-image
        class="!w-[57px] !h-[57px] rounded-[57px] overflow-hidden"
        :src="netAvatar(item.Avatar)"
      />
    </div>
    <div class="flex-1 w-0 ml-[16px] flex flex-col justify-between">
      <div class="text-[15px] truncate">{{ item.Note || item.NickName || "--" }}</div>
      <div class="text-[#bbb] truncate">账号：{{ item.Name }}</div>
      <div class="text-[#bbb] truncate">
        最近上线：{{ userTimeAgo(new Date(formatDate(item.LastMsgTime))) }}
      </div>
    </div>
    <div class="w-[22px] mr-[10px] flex">
      <span
        class="w-[22px] h-[22px] rounded-full text-[12px] bg-[red] text-[#fff] flex justify-center items-center"
        v-if="item.Count > 0"
      >
        {{ item.Count > 99 ? "+99" : item.Count }}
      </span>
    </div>
    <van-popover overlay v-model:show="showPopover" :placement="placement">
      <div class="popover-list">
        <ul @click.stop>
          <li @click="handleShowNote">修改会员备注</li>
          <li @click="handleShowStatus">修改会员状态</li>
          <li @click="handleDelete">删除会员聊天</li>
        </ul>
      </div>
      <template #reference>
        <div class="flex flex-col items-end justify-between" @click.stop="handleShowPopover">
          <van-icon name="ellipsis" class="!text-[28px]" color="#999" />
          <van-button
            class="!text-[12px]"
            :type="userStatusMap[item.Status].type as ButtonType"
            size="mini"
          >
            {{ userStatusMap[item.Status].text }}
          </van-button>
        </div>
      </template>
    </van-popover>
  </div>
  <!-- 会员备注 -->
  <van-dialog
    v-model:show="noteState.show"
    title="修改会员备注"
    show-cancel-button
    :beforeClose="handleBeforeClose"
  >
    <ul class="note-dialog-ul">
      <li>
        <div>会员账号</div>
        <div>{{ item.Name }}</div>
      </li>
      <li>
        <div>会员昵称</div>
        <div>{{ item.NickName || "--" }}</div>
      </li>
      <li>
        <div>会员备注</div>
        <div>
          <van-field class="!w-[full]" v-model="noteState.note" placeholder="请输入会员备注" />
        </div>
      </li>
    </ul>
  </van-dialog>
  <!-- 会员状态 -->
  <van-popup v-model:show="statusState.show" position="bottom" round>
    <div class="status-popup-box">
      <ul>
        <li class="item text-green" @click="handleChangeStatus(1)">正常</li>
        <li class="item text-red" @click="handleChangeStatus(0)">停用</li>
        <li class="item text-red" @click="handleChangeStatus(2)">禁言</li>
        <li class="item text-red" @click="handleChangeStatus(3)">禁止加入房间</li>
      </ul>
      <div class="h-[10px] bg-[#E4E4E4]"></div>
      <div class="item !border-0" @click="statusState.show = false">取消</div>
    </div>
  </van-popup>
</template>
<script setup lang="ts">
import { reqChatContentDel } from "@/api/main";
import { reqUserBan, reqUserNoteEdit } from "@/api/user";
import { userStatusMap } from "@/constants";
import { useServiceStore } from "@/store/modules/service";
import { netAvatar, userTimeAgo, formatDate } from "@/utils/common";
import { toast } from "@/utils/toast";

const props = withDefaults(
  defineProps<{
    item: ChatContentMo;
    last: boolean;
  }>(),
  {
    last: false
  }
);
const router = useRouter();
const serviceStore = useServiceStore();
const showPopover = ref(false);
const bottom = ref(500);
const noteState = reactive({
  show: false,
  note: ""
});

const placement = computed(() => {
  return bottom.value < 140 ? "top-end" : "bottom-end";
});

const handleShowPopover = (event: MouseEvent) => {
  const clickY: number = event.clientY; // 点击位置距离视口顶部的距离
  const viewportHeight: number = window.innerHeight; // 视口高度
  const distanceFromBottom: number = viewportHeight - clickY; // 距离屏幕底部的距离
  bottom.value = distanceFromBottom;
  nextTick(() => {
    showPopover.value = true;
  });
};

const handleShowNote = () => {
  showPopover.value = false;
  noteState.show = true;
};

// 修改备注
const handleBeforeClose = async (action: "confirm" | "cancel") => {
  return new Promise<boolean>(async resolve => {
    if (action == "confirm") {
      if (!noteState.note) {
        toast.info("请输入会员备注");
        resolve(true);
      } else {
        try {
          await reqUserNoteEdit({
            UserId: Number(props.item.UserId),
            Note: noteState.note
          });
          toast.success("修改备注成功");
          serviceStore.updateServiceItem({
            ...props.item,
            Note: noteState.note
          });
          resolve(true);
        } catch (error) {
          resolve(true);
        }
      }
    } else {
      resolve(true);
    }
  });
};

const statusState = reactive({
  show: false
});

const handleShowStatus = () => {
  showPopover.value = false;
  statusState.show = true;
};

// 修改状态
const handleChangeStatus = async (key: number) => {
  const loading = toast.loading("修改中...");
  try {
    await reqUserBan({
      UserId: Number(props.item.UserId),
      Status: key
    });
    toast.success("修改状态成功");
    loading.close();
    statusState.show = false;
    serviceStore.updateServiceItem({
      ...props.item,
      Status: key
    });
  } catch (error) {
    loading.close();
    console.log(error);
  }
};

// 删除聊天
const handleDelete = () => {
  showPopover.value = false;
  showConfirmDialog({
    message: "删除后会清空与该会员的聊天记录，确认要删除与该会员的聊天吗？（同时删除聊天记录）",
    beforeClose: action => {
      return new Promise(async resolve => {
        if (action == "confirm") {
          try {
            await reqChatContentDel({
              Id: props.item.Id
            });
            toast.success("删除成功");
            serviceStore.removeService(props.item);
            resolve(true);
          } catch (error) {
            resolve(true);
          }
        } else {
          resolve(true);
        }
      });
    }
  });
};

// 跳转到聊天详情页面
const handleJump = () => {
  serviceStore.updateServiceCountItem(Number(props.item.UserId), true);
  router.push({
    path: `/admin/main/chat-room`,
    query: {
      uid: props.item.UserId,
      contentId: props.item.Id,
      name: props.item.Note || props.item.NickName || props.item.Name
    }
  });
};
</script>
<style scoped>
.chat-item {
  @apply flex items-center justify-between bg-[#fff] py-[10px] px-[15px];
}
.popover-list ul li {
  @apply py-[10px] text-center px-[15px] border-solid border-b-[1px] border-[#E4E4E4] text-[14px];
}
.note-dialog-ul {
  @apply py-[5px];
}
.note-dialog-ul li {
  @apply flex justify-between items-center text-[14px] text-[#999] py-[10px];
}
.note-dialog-ul li > div:first-child {
  @apply w-[70px] text-right;
}
.note-dialog-ul li > div:last-child {
  @apply flex-1 w-0 ml-[6px] mr-[10px];
}
.note-dialog-ul li > div:last-child .van-field {
  @apply rounded-[6px] py-[6px] px-[10px] text-[14px];
}
.status-popup-box {
  @apply py-[5px];
}
.status-popup-box .item {
  @apply h-[50px] text-[14px] text-center leading-[50px] border-solid border-b-[1px] border-[#E4E4E4];
}
</style>
